package com.aijk.commons.web.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by ChenDeWei on 2016/5/24.
 */
public class ParamsUtils {


    /**
     * 获取reqqquest参数
     *
     * @param request
     * @return
     */
    public static HashMap<String, String> getParams(HttpServletRequest request) {
        // HashMap参数处理
        HashMap paramsMap = new HashMap<String, String>();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String value = entry.getValue()[0];
            if (value != null) {
                paramsMap.put(entry.getKey(), value);
            }
        }
        return paramsMap;
    }

    /**
     * 获得参数Map
     *
     * @param request
     * @return
     */
    public static final Map<String, Object> getParameterMap(HttpServletRequest request) {
        return WebUtils.getParametersStartingWith(request, null);
    }

    /**
     * 获取reqqquest参数
     *
     * @param request
     * @return
     */
    public static HashMap<String, String> getParamsAPi(HttpServletRequest request) {
        // HashMap参数处理
        HashMap paramsMap = new HashMap<String, String>();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String value = entry.getValue()[0];
            if (value != null) {
                paramsMap.put(entry.getKey(), value);
            }
        }
        return paramsMap;
    }

    public static String getParamStr(Map<String, String> map) {
        String url = "";
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> param : entrys) {
            url += "&" + (param.getKey()) + "=" + param.getValue();
        }
        return StringUtils.length(url) > 0 ? url.substring(1) : url;
    }
}
